package edu.biwu.dao.impl;

import edu.biwu.dao.ProductDao;
import edu.biwu.po.Product;
import edu.biwu.utils.ConnectionFactory;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 王俊彪
 * @version 1.0
 */
@Repository
public class ProductDaoImpl implements ProductDao {

    /*将来交给spring 去注入*/
    @Resource
    private QueryRunner queryRunner;
    @Autowired
    private ConnectionFactory connectionFactory;

    @Override
    public void saveProduct(Product product) {
        try {
            queryRunner.update(connectionFactory.currentThreadConn(),"INSERT INTO spring.product" +
                    "(PNAME, PRICE, CATEGORY) VALUES(?,?,?)",
                    product.getPname(),product.getPrice(),product.getCategory());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public void updateProduct(Product product) {
        try {
            queryRunner.update(connectionFactory.currentThreadConn(),"UPDATE spring.product SET pname=?,price=?,category=? WHERE " +
                    " pid = ?",product.getPname(),product.getPrice(),product.getCategory(),product.getPid());
//            int i = 1/0;
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public void deleteProductById(int id) {
        try {
            queryRunner.update(connectionFactory.currentThreadConn(),"DELETE FROM spring.product WHERE pid = ?",id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<Product> findAll() {
        try {
            return queryRunner.query(connectionFactory.currentThreadConn(),"SELECT * FROM spring.product",
                    new BeanListHandler<Product>(Product.class));
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage());
        }

    }

    public ProductDaoImpl(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    public ProductDaoImpl() {
    }

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }
}
